<template>
  <div class="template-content">
    <div class="layout">
      <Layout :style="{minHeight: '100vh'}">
        <Sider collapsible :collapsed-width="0" v-model="isCollapsed" :style="{background: '#e0e0e0',width: '400px'}" class="ivu-card ivu-card-bordered">
<!--          <Devicetree ref="deviceTree" @on-playbtnclick="play" @on-select-change="selectChange"/>-->
        </Sider>
        <Layout :style="{padding: '0 10px 10px'}">
          <Content :style="{padding: '10px', minHeight: '680px', background: '#fff'}">
            <div class="baidumap" id="allmap"></div>
          </Content>
        </Layout>

      </Layout>
    </div>
  </div>
</template>
<script>
//import {Map} from "../../map/baidumap";
import {getMapInfo} from "@/api/mapinfo";
import {apiResult} from "@/libs/util";
export default {
  name: 'futureBuild',
  data(){
    return{
      mapInfo: {
        centerLongitude:114.236262,
        centerLatitude:22.677236,
        minZoom:2,
        maxZoom:20,
        mode: 'ONLINE'
      },
      map:null,
      distribute:null, //围栏实体类
      isCollapsed:true,
      baseUrl: process.env.BASE_URL,
      build: "此页还在建设中......"
    }
  },
  mounted() {
    getMapInfo().then(res => {
        apiResult(res.data,false,result=>{
          this.mapInfo = result.data;
        })

    })
    this.createBaiduMap();

    this.distribute = new distributeData();
    //this.distribute.context = context;
    //this.build="页面 <<" + this.$route.meta.title + ">> 还在建设中......"
  },
  methods:{
    play(){

    },
    selectChange(){

    },
    createBaiduMap(){
      let that = this;
      that.map = new BMap.Map("allmap",{minZoom:that.mapInfo.minZoom.minZoom,maxZoom:that.mapInfo.maxZoom});            // 创建Map实例
      let point = new BMap.Point(that.mapInfo.centerLongitude,that.mapInfo.centerLatitude); // 创建点坐标
      /*
              var marker=new BMap.Marker(point);
              map.addOverlay(marker);//添加一个标注
      */
      that.map.centerAndZoom(point,13);//添加初始化中心点及地图层级
      that.map.enableScrollWheelZoom();//开启鼠标滚轮缩放功能。仅对PC上有效
      that.map.enableContinuousZoom();//启用连续缩放效果，默认禁用

      that.map.addControl(new BMap.NavigationControl()); //地图导航控制
      that.map.addControl(new BMap.ScaleControl());
      that.map.addControl(new BMap.OverviewMapControl());
      that.map.addControl(new BMap.MapTypeControl());

      drawsMaps(that.map);
      //第一种方式引入
/*      Map().then( BMap => {				//调用map.js中Map()方法，引入百度地图秘钥作为参数

        let that = this;
        that.map = new BMap.Map("allmap",{minZoom:that.mapInfo.minZoom.minZoom,maxZoom:that.mapInfo.maxZoom});            // 创建Map实例
        let point = new BMap.Point(that.mapInfo.centerLongitude,that.mapInfo.centerLatitude); // 创建点坐标
        /!*
                var marker=new BMap.Marker(point);
                map.addOverlay(marker);//添加一个标注
        *!/
        that.map.centerAndZoom(point,13);//添加初始化中心点及地图层级
        that.map.enableScrollWheelZoom();//开启鼠标滚轮缩放功能。仅对PC上有效
        that.map.enableContinuousZoom();//启用连续缩放效果，默认禁用

        that.map.addControl(new BMap.NavigationControl()); //地图导航控制
        that.map.addControl(new BMap.ScaleControl());
        that.map.addControl(new BMap.OverviewMapControl());
        that.map.addControl(new BMap.MapTypeControl());
        //that.map.setMapStyle({ style: 'midnight' })//地图风格

        drawsMaps(that.map);
      })*/
    },
  }
}

let distributeData = function(target){
  let me = this;
  let containsRecs=[];
  let markers=[];
  /** 当前围栏 */
  let currentPoly=null;
  let recorders=[];

  //由权限取得所有执法仪数据
  me.map=null; //地图

  /** 判断是否在围栏里*/
  me.posInEclosure=function(){
    var rec=null;
    containsRecs.length = 0;
    for (var i = 0; i < recorders.length; i++) {
      rec = recorders[i];
      var pr = new BMap.Point(rec.attributes.lon, rec.attributes.lat);// 判断点的坐标，可以动态的获取到，这里设置的是一个固定点
      var pp = GpsToBaiduPoint(pr);
      /** 是否在围栏里 */
      let found = BMapLib.GeoUtils.isPointInPolygon(pp, currentPoly); // 判断一个点是否在多边形区域内，返回的结果是一个布尔值
      if (found == true) {
        containsRecs.push(rec);
      }
    }
    //显示所有在围栏内的设备
    me.refreshTree();
  }

  me.setRecorders=function(data){
    recorders.length=0;
    recorders=data;
    posInEclosure();
  }
  /** 查看所有设备 */
  me.setAllRecorders=function(data){
    me.clearMarker();//清除所有标注
    /** 清除原围栏 */
    if (currentPoly != null){
      map.removeOverlay(currentPoly);
    }
    recorders.length=0;
    recorders=data;
    containsRecs.length = 0;
    for (var i = 0; i < recorders.length; i++) {
      containsRecs.push(recorders[i]);
    }
    me.refreshTree();
  }

  /** 刷新列表 */
  me.refreshTree=function(){
    $("#enclosures").tree({
      data:containsRecs,
      required: true,
      checkbox: true,
      animate:true,
      onBeforeCheck:function(node,checked){
        return true;
      },
      onCheck:function(node,checked){
        if (checked == true){
          /** 显示设备 */
          me.createMarker(node);
        }else{
          /** 隐藏设备 **/
          me.removeMarker(node);
        }
      },
      onLoadSuccess: function (node, data) {},
      //点击事件
      onClick: function(node){
        //移到中心点
        if (node.checked == false){
          $('#enclosures').tree('check',node.target);
        }
        me.center(node);
      },
    });

    /** 为在线和离线变颜色显示 */
    for (var i=0;i<containsRecs.length;i++){
      var node = $('#enclosures').tree('find', containsRecs[i].id);
      var style = "";
      if (node){
        if (node.attributes.policeCode != null){
          var img = "";
          if (node.attributes.status=="online"){
            img = "/man_user.png";
          }else{
            img = "/l_user.png";
          }
          //style = '<img src="right_page/wirelesscharges/images/'+img+'" style="width:15px;margin-right:5px;" />';
          style = '<img src="'+ process.env.BASE_URL + '/images/'+img+'" style="width:15px;margin-right:5px;" />';
        }
        var color="";
        if (node.attributes.status=="online"){
          color = "green;";
        }else{
          color = "#000;";
        }
        style += '<span class="tree_span" style="color:'+color+'">'+node.text+'</span>';
        $('#enclosures').tree('update',{
          target: node.target,
          text: style
        });
      }
    }
  }
  /** 画栏结束 */
  me.finish = function(overlay){
    if (currentPoly != null){
      map.removeOverlay(currentPoly);
    }
    currentPoly = overlay;
  }

  /** 建标注点 */
  me.createMarker=function(node) {
    var p = new BMap.Point(node.attributes.lon,node.attributes.lat);
    var myIcon = new BMap.Icon(process.env.BASE_URL +"/right_page/wirelesscharges/img/ditu.png",
      new BMap.Size(23, 25), {
        offset: new BMap.Size(10, 25)
      });
    var mkr = new BMap.Marker(p,{icon:myIcon});
    me.map.addOverlay(mkr); // 标点
    var label = new BMap.Label(node.attributes.policeName, {
      offset : new BMap.Size(20, -10),
    });
    mkr.setLabel(label);
    markers.push({id:node.id,marker:mkr});
    //500毫秒后停止
    setTimeout(function(){mkr.setAnimation(BMAP_ANIMATION_DROP)}, 500);
  }
  /** 隐藏某个标注点 */
  me.removeMarker=function(node) {
    for (var i = 0; i < markers.length; i++) {
      if(markers[i].id == node.id){
        me.map.removeOverlay(markers[i].marker);
        markers.splice(i,1);
        return;
      }
    }
  }
  /** 清除所有标注点 */
  me.clearMarker=function() {
    for (var i = markers.length-1; i >= 0; i--) {
      me.map.removeOverlay(markers[i].marker);
    }
    markers.length=0;
  }
  /** 转到中心点 */
  me.center=function(node){
    var zoom = map.getZoom();
    me.map.centerAndZoom(new BMap.Point(node.attributes.lon,node.attributes.lat), zoom);
  }
}
function drawsMaps(map){
  // 绘图的样式
  var styleOptions = {
    strokeColor : "red", // 边线颜色。
    fillColor : "green", // 填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight : 3, // 边线的宽度，以像素为单位。
    strokeOpacity : 0.8, // 边线透明度，取值范围0 - 1。
    fillOpacity : 0.3, // 填充的透明度，取值范围0 - 1。
    strokeStyle : 'solid' // 边线的样式，solid或dashed。
  }
  console.log(window.BMapLib);
  // 实例化鼠标绘制工具
  var drawingManager = new window.BMapLib.DrawingManager(map, {
    isOpen : false, // 是否开启绘制模式
    enableDrawingTool : true, // 是否显示工具栏
    drawingToolOptions : {
      anchor : BMAP_ANCHOR_TOP_LEFT, // 位置
      offset : new BMap.Size(5, 5), // 偏离值
      drawingModes : [BMAP_DRAWING_CIRCLE,BMAP_DRAWING_POLYGON,BMAP_DRAWING_RECTANGLE],
      drawingTypes:[
        BMAP_DRAWING_CIRCLE,//圆的样式
        //BMAP_DRAWING_POLYLINE,//线的样式
        BMAP_DRAWING_POLYGON,//多边形的样式
        BMAP_DRAWING_RECTANGLE //矩形的样式
      ]
    },

    circleOptions: styleOptions, //圆的样式
    polygonOptions: styleOptions, //多边形的样式
    rectangleOptions: styleOptions //矩形的样式
  });

  // 鼠标绘制完成回调方法 获取各个点的经纬度
  var overlaycomplete = function(e) {
    layer.open({
      anim : 1, // 默认动画风格
      skin : 'layui-layer-lan', // 默认皮肤
      title : '人力分布图',
      content : '确定该区域已画好,是否需要重新画',
      btn : [ '确定', '取消' ],
      yes : function(index, layero) {

        if(typeof(drawingManager) != 'undefined'){
          drawingManager.close();
        }
        distribute.finish(e.overlay);
        distribute.clearMarker();
        layer.close(index);
        $.ajax({
          url : context + "/4g/getPoliceDistribute?ram="+ Math.random(),
          type : "post",
          contentType : "application/json",
          dataType : "json",
          async : false,
          success : function(data) {
            if (data.success==false){
              layer.msg(data.msg);
            }else if(data.length == 0){
              layer.msg('当前所选区域没有上线的记录仪。', {icon: 6,time:2000});
            }else{
              var baidu_p;
              /** 转百度坐标 */
              for(var i = 0; i < data.data.length; i++){
                baidu_p = GpsToBaiduPoint(new BMap.Point(data.data[i].attributes.lon,data.data[i].attributes.lat));
                data.data[i].attributes.lon = baidu_p.lng;
                data.data[i].attributes.lat = baidu_p.lat;
              }
              distribute.setRecorders(data.data);
            }
          }
        });

      },
      cancel : function() {
        if (e.overlay != null){
          map.removeOverlay(e.overlay);
        }
      }
    });

  };


//	绘制矩形完成后，派发的事件接口
  var rectanglecomplete = function(e) {
    cameras.length=0;
    deletenclosure();
    clearNarkers();

  };

  //	绘制圆完成后，派发的事件接口
  let circlecomplete = function(e) {
    cameras.length=0;
    deletenclosure();
    clearNarkers();
  };

  //	绘制多边形完成后，派发的事件接口
  let polygoncomplete = function(e) {
    cameras.length=0;
    deletenclosure();
    clearNarkers();
  };

  drawingManager.addEventListener('overlaycomplete', overlaycomplete);
}
</script>
<style lang="less">
  @import ".././template";
  .layout-con{
    height: 100%;
    width: 100%;
  }
  .ivu-layout-sider-trigger {
    position: fixed;
    bottom: 0;
    text-align: center;
    cursor: pointer;
    height: 48px;
    line-height: 48px;
    color: #252525;
    background: #f3f3f3;
    z-index: 1000;
    -webkit-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
  }
  .ivu-tree-title {
    display: inline-block;
    margin: 0;
    padding: 0 4px;
    border-radius: 3px;
    cursor: pointer;
    vertical-align: top;
    color: #45f803;
    -webkit-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
  }

  .top_nav_01{
    z-index: 999999999;
  }
  .baidumap {
    width: 100%;
    height: 100%;
    border: none;
    position: inherit;
    left:0px;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background-color: #2d8cf0;
    overflow: hidden;
    z-index: 0;
  }

  /* 去除百度地图版权那行字 和 百度logo */
  .baidumap > .BMap_cpyCtrl {
    display: none !important;
  }
  .baidumap > .anchorBL {
    display: none !important;
  }
</style>
